package com.killer.conf;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.RabbitListenerContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;


@Configuration
public class RabbitConfig {

    /**
     * 声明正常业务队列
     * @return
     */
    @Bean
    public Queue bizQueue(){
        Map<String,Object> props=new HashMap<String,Object>();
        //消息的生存时间 10s
        props.put("x-message-ttl", 10000);
        //设置该队列所关联的死信交换器(当队列消息TTL到期后依然没有消费，则加入死信队列）
        props.put("x-dead-letter-exchange", "ex.dl");
        //设置该队列所关联的死信交换器的routinkey,如果灭有特殊指定，使用原来队列的routingkey
        props.put("x-dead-letter-routing-key", "rk.dl");
        //创建队列，指定对应参数
        Queue queue = new Queue("queue.biz", true, false, false, props);
        return queue;
    }

    /**
     * 声明死信队列
     * @return
     */
    @Bean
    public Queue dlQueue(){
        Queue queue = new Queue("queue.dl", true, false, false, null);
        return queue;
    }

    /**
     * 声明普通业务交换器
     * @return
     */
    @Bean
    public Exchange bizExchange(){
        DirectExchange exchange = new DirectExchange("ex.biz", true, false, null);
        return exchange;
    }

    /**
     * 声明死信交换器
     * @return
     */
    @Bean
    public Exchange dlExchange(){
        DirectExchange exchange = new DirectExchange("ex.dl", true, false, null);
        return exchange;
    }

    /**
     * 声明业务交换器与业务队列的绑定
     * @return
     */
    @Bean
    public Binding bizBinding(){
        Binding binding = new Binding("queue.biz", Binding.DestinationType.QUEUE, "ex.biz", "rk.biz", null);
        return binding;
    }

    /**
     * 声明死信交换器与死信队列的绑定
     * @return
     */
    @Bean
    public Binding dlBinding(){
        Binding binding = new Binding("queue.dl", Binding.DestinationType.QUEUE, "ex.dl", "rk.dl", null);
        return binding;
    }

    /**
     * 声明以及配置rabbit监听器属性
     * @param connectionFactory
     * @return
     */
    @Bean
    public RabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory=new SimpleRabbitListenerContainerFactory();
        simpleRabbitListenerContainerFactory.setConnectionFactory(connectionFactory);
        //设置ack方式为手动ack
        simpleRabbitListenerContainerFactory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return simpleRabbitListenerContainerFactory;
    }

}
